package com.github.prontera.controller;

import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.prontera.ApiVersion;
import com.github.prontera.common.filter.CurrentUserId;
import com.github.prontera.domain.Role;
import com.github.prontera.domain.User;
import com.github.prontera.model.response.ObjectDataResponse;
import com.github.prontera.model.response.Response;
import com.github.prontera.service.RoleService;
import com.github.prontera.service.UserService;
import com.github.prontera.util.Page;

/**
 * 角色管理
 * @author Alex
 */
@RestController
@RequestMapping(value = ApiVersion.MANAGE_V1_PREFIX + "/role", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE }, consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public class RoleController {

	@Autowired
	private RoleService roleService;
	@Autowired
	private UserService userService;

	//@MagicPermission 接口权限
	@ApiOperation(value = "查询角色信息", notes = "查询角色信息")
	@RequestMapping(value = "/queryRole", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<Role>> queryRole(@RequestBody Role role) {
		
		Page<Role> datas = roleService.page(role);
		return new ObjectDataResponse<Page<Role>>(datas);
	}



	@ApiOperation(value = "修改角色内容", notes = "修改角色内容")
	@RequestMapping(value = "/updateRole", method = RequestMethod.POST)
	@ResponseBody
	public Response updateRole(@CurrentUserId Long userId, @RequestBody Role role) {
		User user = new User();
		user.setId(userId);
		role.setUpdateUser(userService.find(user).get(0).getUsername());
		int success = roleService.updateRole(role);
		return new ObjectDataResponse<Integer>(success);
	}

	@ApiOperation(value = "添加角色内容", notes = "添加角色内容")
	@RequestMapping(value = "/addRole", method = RequestMethod.POST)
	@ResponseBody
	public Response addRole(@CurrentUserId Long userId, @RequestBody Role role) {
		User user = new User();
		user.setId(userId);
		role.setCreateUser(userService.find(user).get(0).getUsername());
		int success = roleService.insertRole(role);
		return new ObjectDataResponse<Integer>(success);
	}


	@ApiOperation(value = "删除角色内容", notes = "删除角色内容")
	@RequestMapping(value = "/deleteRole", method = RequestMethod.POST)
	@ResponseBody
	public Response deleteRole(@CurrentUserId Long userId, @RequestBody Role role) {
		int success = roleService.deleteByRoleId(role);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", success);
		if(success == 2){
			map.put("msg", "该角色被用户所使用，无法被删除！");	
		}
		return new ObjectDataResponse<Object>(map);
	}

	

}
